package com.luomo.java.juc.lock;

import java.util.concurrent.TimeUnit;

/**
 * @author LiuMei
 * @date 2021-04-14.
 */
public class DeadLockDemo {

    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";

        new Thread(new HoldLockThread(lockA,lockB),"A").start();
        new Thread(new HoldLockThread(lockB,lockA),"B").start();

        /**
         * linux ps -ef|grep xxxx        ls -l
         * windows下的java运行程序，类似ps的查看进程的命令，查看的只是java
         *
         * jps = java ps        jps -l 查看java进程  jstack pid 查看进程stack信息
         */
    }

}

class HoldLockThread implements Runnable{

    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+"\t自己持有"+lockA+"锁");
            try {
                TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
            System.out.println(Thread.currentThread().getName()+"\t尝试获取"+lockB+"锁");
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+"\t自己持有"+lockB+"锁");
            }
        }
    }
}
